package com.xiaoma.verbal.service;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xiaoma.tpo.service.UserService;
import com.xiaoma.tpo.utils.Pager;
import com.xiaoma.verbal.dao.PrctPracticeAudioDao;
import com.xiaoma.verbal.dao.QuQuestionDao;
import com.xiaoma.verbal.dao.QuTpoDao;
import com.xiaoma.verbal.domain.QuQuestion;
import com.xiaoma.verbal.domain.QuTpo;
import com.xiaoma.verbal.dto.QuTpoVo;
import com.xiaoma.verbal.dto.TpoTaskVo;
import com.xiaoma.verbal.dto.TpoVo;
import com.xiaoma.verbal.utils.Constants;
import com.xiaoma.verbal.utils.ExcelUtil;
import com.xiaoma.verbal.utils.MemoryDB;
import com.xiaoma.verbal.utils.UUIDGenerator;

@Service
public class QuTpoService extends BaseQuestionService {
	@Autowired
	private QuQuestionDao quQuestionDao;
	@Autowired
	private QuTpoDao quTpoDao;
	@Autowired
	private QuestionService questionService;
	@Autowired
	private PrctPracticeAudioDao prctPracticeAudioDao;

	@SuppressWarnings("unchecked")
	public List<Integer> findTpoTasks() {
		return this.quTpoDao.findTpoTasks();
	}

	public List<QuTpoVo> findTpoTaskQuestions(Integer taskNum) {
		return this.quTpoDao.findTpoTaskQuestions(taskNum);
	}

	public Boolean hasUpdate(Long lastUpdateTime, TpoVo vo, Boolean cacheAble) {
		if (lastUpdateTime == null)
			return true;

		Long timeCoordinate = 0L;

		if (cacheAble) {
			timeCoordinate = (Long) MemoryDB.get(Constants.QTTC);
		} else {
			timeCoordinate = this.quTpoDao.getTimeCoordinate();
		}
		vo.setUpdateTime(timeCoordinate);

		if (lastUpdateTime.longValue() != timeCoordinate.longValue()) {
			return true;
		}

		return false;
	}

	public Long getTimeCoordinate() {
		return this.quTpoDao.getTimeCoordinate();
	}

	@SuppressWarnings("unchecked")
	public List<TpoTaskVo> findTpos() {
		List taskVos = new ArrayList<TpoTaskVo>();
		// List<Integer> tasks = quTpoDao.findTpoTasks();
		Integer[] tasks = { 1, 2 };

		for (Integer taskNum : tasks) {
			TpoTaskVo task = new TpoTaskVo();
			List<QuTpoVo> tpo = quTpoDao.findTpoTaskQuestions(taskNum);
			task.setTaskNum(taskNum);
			task.setQuestions(tpo);
			taskVos.add(task);
		}
		return taskVos;
	}

	@SuppressWarnings("unchecked")
	public TpoVo findTposBycheckUpdate(Boolean checkUpdate, Long lastUpdateTime) {
		TpoVo vo = new TpoVo();
		if (checkUpdate != null && checkUpdate) {
			if (this.hasUpdate(lastUpdateTime, vo, true)) {
				vo.setTaks(this.findTpos());
				vo.setHasUpdate(true);
				vo.setUpdateTime(this.getTimeCoordinate());
				return vo;
			}
		}
		vo.setTaks(new ArrayList<TpoTaskVo>());
		vo.setHasUpdate(false);
		vo.setUpdateTime(lastUpdateTime);
		return vo;

	}

	public Pager list(Integer id, String qnum, Integer taskNum, Integer tpoNum, String tagText, String content, Integer page, Integer pageSize) {
		if (page == null || page == 0) {
			page = 1;
			pageSize = 50;
		}
		Pager pager = quTpoDao.queryPageList(id, qnum, taskNum, tpoNum, tagText, content, (page - 1) * pageSize, pageSize);

		return pager;
	}

	public int importData(int version, InputStream fis) // TODO Auto-generated
			// method stub
			throws Exception {
		// TODO Auto-generated method stub
		List<Map<String, Object>> list = null;
		try {
			// excel数据
			if (version == 2003) {
				list = ExcelUtil.parseExcel_2003(fis);
			} else {
				list = ExcelUtil.parseExcel_2007(fis);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return 2;
		}
		try {
			// 保存数据
			for (Map<String, Object> m : list) {
				saveDate(m, 3);
			}
		} catch (Exception e) {
			throw e;
		}
		return 1;
	}

	private void saveDate(Map<String, Object> map, int type) throws Exception {
		final String qNum = (String) map.get("question_num");
		final String idstr = (String) map.get("qid");// 导入时此项不存在

		if (qNum != null && qNum.length() > 0) {
			// 保存或更新题
			// 导入时通过题号判断是否已存在，存在的话则覆盖
			QuQuestion oldqb = this.quQuestionDao.findByQnum(qNum);
			if (oldqb != null) {
				if (type == 3) {
					dealKyQb(oldqb, map, type);
				}
			} else {
				QuQuestion qb = new QuQuestion();
				// id不为空则更新
				if (idstr != null && idstr.length() > 0) {
					qb.setId(Integer.parseInt(idstr));
				}
				if (type == 3) {
					dealKyQb(qb, map, type);
				}
			}
		}

	}

	/**
	 * 处理题库--口语
	 * 
	 * @param qb
	 * @throws Exception
	 */
	@SuppressWarnings("deprecation")
	private void dealKyQb(QuQuestion qb, Map<String, Object> rowmap, int type) throws Exception {

		final String idstr = (String) rowmap.get("qid");// 导入时此项不存在,单个修改时才不为空
		final String qNum = (String) rowmap.get("question_num");
		final String content = (String) rowmap.get("content").toString().replaceAll("\'", "\\\\'");
		final String tags = (String) rowmap.get("tags");
		final String translation = (String) rowmap.get("translation");
		final String keyword_audiourls = (String) rowmap.get("keyword_audiourl");
		final String review = (String) rowmap.get("review");// 老师点评
		final String task_num = rowmap.get("question_num").toString().split("-")[1];
		final String tpo_num = rowmap.get("tpo_num").toString().replaceAll("TPO", "");
		String time_limit = "45";
		if (task_num.trim().equals("1") || task_num.trim().equals("2")) {
			time_limit = "45";
		} else {
			time_limit = "60";
		}

		if (!qNum.startsWith("T")) {
			// 错误，口语是以S_开头
			throw new Exception("内容有误，应该上传口语");
		}

		qb.setQuestionNum(qNum);
		if ((content != null && content.length() > 0) || idstr != null) {
			qb.setContent(content);
		}

		if ((translation != null && translation.length() > 0) || idstr != null) {
			qb.setTranslation(translation);
		}
		qb.setQuestionType(type);

		if (qb.getId() != null && qb.getId() > 0) {
			qb.setUpdateTime(new Date());
		} else {
			Date date = new Date();
			qb.setCreateTime(date);
			qb.setUpdateTime(date);
		}
		if (qb.getId() != null) {
			this.quQuestionDao.update(qb);

		} else {
			qb.setId(quQuestionDao.insert(qb));
		}

		// 题库标签
		this.questionService.dealTags(qb, tags, idstr, type);
		this.dealTpo(qb, task_num, tpo_num);
	}

	private void dealTpo(QuQuestion qb, String taskNum, String tpoNum) {
		QuTpo tpo = new QuTpo();
		tpo.setQuestionId(qb.getId());
		List<QuTpo> tpos = this.quTpoDao.findByColumns(tpo);
		String uuid = null;
		if (!CollectionUtils.isEmpty(tpos)) {
			for (QuTpo del : tpos) {
				uuid = del.getUuid();
				this.quTpoDao.destroy(del.getId());
			}
		}
		Date date = new Date();
		tpo.setCreateTime(date);
		tpo.setUpdateTime(date);
		tpo.setQuestionId(qb.getId());
		tpo.setUuid(uuid != null ? uuid : UUIDGenerator.getUUID());
		if (taskNum != null && !"".equals(taskNum)) {
			tpo.setTaskNum(Integer.valueOf(taskNum));
		}

		if (tpoNum != null && !"".equals(tpoNum)) {
			tpo.setTpoNum(Integer.valueOf(tpoNum));
		}

		this.quTpoDao.insert(tpo);
	}

	public int checkQnumIsExist(String questionNum) {
		// TODO Auto-generated method stub
		return this.questionService.checkQnumIsExist(questionNum);

	}

	public void save(Integer qid, String questionType, String questionNum, String content, String qtags, String translation, Integer tpoNum, Integer taskNum) {
		// TODO Auto-generated method stub
		QuQuestion qb = new QuQuestion();
		qb.setQuestionNum(questionNum);
		qb.setContent(content);
		qb.setTranslation(translation);
		qb.setTimeLimit(45);
		qb.setCreateTime(new Date());
		qb.setUpdateTime(qb.getCreateTime());
		qb.setQuestionType(3);
		qb.setId(this.quQuestionDao.insert(qb));
		this.dealTpo(qb, String.valueOf(taskNum), String.valueOf(tpoNum));
		this.afterChanger();
	}

	public void update(Integer qid, String questionType, String questionNum, String content, String qtags, String translation, Integer tpoNum, Integer taskNum) {
		// TODO Auto-generated method stub
		QuQuestion qb = this.quQuestionDao.getById(qid);
		if (qb != null) {
			qb.setQuestionNum(questionNum);
			qb.setContent(content);
			qb.setTranslation(translation);
			qb.setUpdateTime(new Date());
			qb.setQuestionType(3);
			this.quQuestionDao.update(qb);
			this.dealTpo(qb, String.valueOf(taskNum), String.valueOf(tpoNum));
			this.afterChanger();
		} else {
			return;
		}

	}
	/**
	 * 
	 *新的
	 *
	 */
	//新
	@SuppressWarnings("unchecked")
	public TpoVo findTposBycheckUpdateNew(Boolean checkUpdate, Long lastUpdateTime,Integer userId,Integer ClsClassId) {
		TpoVo vo = new TpoVo();
		if (checkUpdate != null && checkUpdate) {
			if (this.hasUpdate(lastUpdateTime, vo, true)) {
				vo.setTaks(this.findTposNew(userId,ClsClassId));
				vo.setHasUpdate(true);
				vo.setUpdateTime(this.getTimeCoordinate());
				return vo;
			}
		}
		vo.setTaks(new ArrayList<TpoTaskVo>());
		vo.setHasUpdate(false);
		vo.setUpdateTime(lastUpdateTime);
		return vo;

	}
	
	//新
	@SuppressWarnings("unchecked")
	public List<TpoTaskVo> findTposNew(Integer userId,Integer clsClassId) {
		List taskVos = new ArrayList<TpoTaskVo>();
		// List<Integer> tasks = quTpoDao.findTpoTasks();
		Integer[] tasks = { 1, 2 };

		for (Integer taskNum : tasks) {
			TpoTaskVo task = new TpoTaskVo();
			List<QuTpoVo> tpo = quTpoDao.findTpoTaskQuestionsNew(taskNum);
			List<QuTpoVo> tpoNew = new  ArrayList<QuTpoVo>();
			for(QuTpoVo quTpoVo : tpo){
				boolean yonCommit = prctPracticeAudioDao.findbyClsIdAndQuestionNumAndUserId(clsClassId,quTpoVo.getQuestionNum(),userId);
				quTpoVo.setYonCommit(yonCommit);
				
			}
			task.setTaskNum(taskNum);
			task.setQuestions(tpo);
			taskVos.add(task);
		}
		return taskVos;
	}
}
